package com.chagee.store.operation.server.service.biz;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chagee.base.utils.PaginationData;
import com.chagee.base.utils.PaginationRequest;
import com.chagee.personnel.api.event.response.EmployeeResp;
import com.chagee.scm.api.supplier.request.SearchSupplierBaseBO;
import com.chagee.scm.api.supplier.response.SupplierBaseBO;
import com.chagee.store.operation.api.bo.*;
import com.chagee.store.operation.api.request.SearchSupplierRequest;
import com.chagee.store.operation.api.response.SearchSupplierResponse;
import com.chagee.store.operation.common.constant.CommonConstant;
import com.chagee.store.operation.common.exception.BizErrorCode;
import com.chagee.store.operation.common.exception.BizException;
import com.chagee.store.operation.common.utils.ResponseUtil;
import com.chagee.store.operation.server.entity.BasicTaskDO;
import com.chagee.store.operation.server.entity.StoreConfigurationDO;
import com.chagee.store.operation.server.entity.StoreDO;
import com.chagee.store.operation.server.entity.StoreTaskRelationDO;
import com.chagee.store.operation.server.entity.TaskExecutionDO;
import com.chagee.store.operation.server.entity.WorkOrderDO;
import com.chagee.store.operation.server.event.dao.BasicTaskConfigurationMapper;
import com.chagee.store.operation.server.event.dao.StoreConfigurationMapper;
import com.chagee.store.operation.server.event.dao.StoreTaskRelationMapper;
import com.chagee.store.operation.server.event.service.BasicTaskConfigurationService;
import com.chagee.store.operation.server.event.service.StoreConfigurationBaseService;
import com.chagee.store.operation.server.event.service.StoreTaskRelationBaseService;
import com.chagee.store.operation.server.event.service.WorkOrderBaseService;
import com.chagee.store.operation.server.feign.SystemApi;
import com.chagee.store.operation.server.feign.request.ReginRequest;
import com.chagee.store.operation.server.feign.response.SystemResponse;
import com.chagee.store.operation.server.feign.vo.ReginDate;
import com.chagee.store.operation.server.model.info.*;
import com.chagee.store.operation.server.model.lock.*;
import com.chagee.store.operation.server.model.param.StoreTaskRelationDetailParam;
import com.chagee.store.operation.server.model.param.StoreTaskRelationRequest;
import com.chagee.store.operation.server.model.param.UpdateDateRequest;
import com.chagee.store.operation.server.model.response.StoreTaskRelation2SetVO;
import com.chagee.store.operation.server.model.response.StoreTaskRelationDetailResponse;
import com.chagee.store.operation.server.model.response.StoreTaskRelationExistResponse;
import com.chagee.store.operation.server.model.response.StoreTaskRelationResponse;
import com.chagee.store.operation.server.model.response.TaskRelationDetailResponse;
import com.chagee.store.operation.server.redis.service.RedisLockService;
import com.chagee.store.operation.server.service.PersonnelThirdService;
import com.chagee.store.operation.server.service.StorePersonnelBizService;
import com.chagee.store.operation.server.service.base.StoreBaseService;
import com.chagee.store.operation.server.service.third.ScmThirdService;
import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springblade.core.tool.utils.BeanUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author : hk
 * @Date : 2024/7/2
 */

@Slf4j
@Service
@RequiredArgsConstructor
public class StoreTaskRelationBizService {

	private final StoreTaskRelationMapper storeTaskRelationMapper;
	private final StoreBizService storeBizService;
	private final StoreBaseService storeBaseService;
	private final BasicTaskConfigurationMapper basicTaskConfigurationMapper;
	private final BasicTaskConfigurationService basicTaskConfigurationService;
	private final StoreTaskRelationBaseService storeTaskRelationBaseService;
	private final StoreConfigurationMapper storeConfigurationMapper;

	@Value("${threePartyClosing.qrCodeUrl}")
	private String qrCodeUrl;
	@Value("${store-gmv.url}")
	private String gmvUrl;
	@Value("${store-gmv.authorization}")
	private String gmvAuthorization;
	@Value("${store-gmv.storeCode}")
	private String gmvStoreCode;
	@Value("${store-gmv.pt}")
	private String gmvPt;

	//supplierCategoryId = 407
	@Value("${supplier.supplierCategoryId}")
	private String supplierCategoryId;


	@Value("${store.task.multiple}")
	private String multiple;

	@Resource
	private SystemApi systemApi;
	@Resource
	private WorkOrderBaseService workOrderBaseService;
	@Resource
	private StoreConfigurationBaseService storeConfigurationBaseService;
	@Resource
	private RedisLockService redisLockService;

	@Resource
	private ScmThirdService scmThirdService;

	@Resource
	private StorePersonnelBizService storePersonnelBizService;
	@Value("${storeConfig.managerRoleId}")
	private String managerRoleId;
	@Value("${storeConfig.carryOutRoleId}")
	private String carryOutRoleId;

	@Resource
	private PersonnelThirdService personnelThirdService;

	private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	private final SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyyMMdd");

	public StoreTaskRelationDetailResponse queryDetail(StoreTaskRelationRequest request) {
		StoreTaskRelationDetailResponse storeTaskRelationDetailResponse = new StoreTaskRelationDetailResponse();
		StoreDO storeDO = storeBizService.queryStoreByNo(request.getStoreNo());
		if (Objects.nonNull(storeDO)) {
			//门店编码/名称
			storeTaskRelationDetailResponse.setStoreNo(storeDO.getStoreNo());
			storeTaskRelationDetailResponse.setStoreName(storeDO.getStoreName());
			//三方打烊状态
			storeTaskRelationDetailResponse.setClosingTaskStatus(storeDO.getClosingTaskStatus());
			//二维码
			storeTaskRelationDetailResponse.setQrCodeUrl(qrCodeUrl + storeDO.getStoreNo());
			//赋值门店所在市名称
			String region = storeDO.getRegion();
			if (StringUtils.isNotBlank(region)) {
				List<String> list = Arrays.asList(region.split(","));
				if (!org.springframework.util.CollectionUtils.isEmpty(list)) {
					List<Integer> integerList = list.stream().map(Integer::parseInt).collect(Collectors.toList());
					if (!org.springframework.util.CollectionUtils.isEmpty(integerList)) {
						ReginRequest reginRequest = new ReginRequest();
						reginRequest.setCodeList(integerList);
						SystemResponse<List<ReginDate>> listSystemResponse = systemApi.reginNameListQuery(reginRequest);
						List<ReginDate> data = listSystemResponse.getData();
						if (!org.springframework.util.CollectionUtils.isEmpty(data)) {
							storeTaskRelationDetailResponse.setCityName(data.get(1).getName());
						}
					}
				}
			}
			List<String> userIds = new ArrayList<>();
			//赋值：供应商进场日期/计费开始日期/打烊工单创建时间/打烊工单自动验收时间
			List<StoreConfigurationDO> storeConfigurationDOList = storeConfigurationBaseService.getByStoreCode(storeDO.getStoreNo());
			if (CollectionUtils.isNotEmpty(storeConfigurationDOList)) {
				StoreConfigurationDO storeConfigurationDO = storeConfigurationDOList.stream().findFirst().orElseThrow(() -> new BizException(BizErrorCode.STORE_CONFIG_NULL));
				storeTaskRelationDetailResponse.setSupplierEntryDate(storeConfigurationDO.getSupplierEntryDate());
				storeTaskRelationDetailResponse.setBillingStartDate(storeConfigurationDO.getBillingStartDate());
				storeTaskRelationDetailResponse.setClosingWorkOrderCreateTime(storeConfigurationDO.getClosingWorkOrderCreateTime());
				storeTaskRelationDetailResponse.setClosingWorkOrderAcceptanceTime(storeConfigurationDO.getClosingWorkOrderAcceptanceTime());
				storeTaskRelationDetailResponse.setFloorPrice(storeConfigurationDO.getFloorPrice());
				storeTaskRelationDetailResponse.setNightFloorPrice(storeConfigurationDO.getNightFloorPrice());
				storeTaskRelationDetailResponse.setSupplierNo(storeConfigurationDO.getSupplierNo());
				if (Objects.nonNull(storeConfigurationDO.getManage())) {
					List<ManageInfo> manageInfos = JSON.parseObject(storeConfigurationDO.getManage(), new TypeReference<List<ManageInfo>>() {
					});
					storeTaskRelationDetailResponse.setManageList(manageInfos);
					List<String> manageIds = manageInfos.stream().filter(Objects::nonNull).map(ManageInfo::getManageId).collect(Collectors.toList());
					userIds.addAll(manageIds);
				}
				if (Objects.nonNull(storeConfigurationDO.getCarryOut())) {
					List<CarryOutInfo> carryOutInfos = JSON.parseObject(storeConfigurationDO.getCarryOut(), new TypeReference<List<CarryOutInfo>>() {
					});
					storeTaskRelationDetailResponse.setCarryOutList(carryOutInfos);
					List<String> carryOutIds = carryOutInfos.stream().filter(Objects::nonNull).map(CarryOutInfo::getCarryOutId).collect(Collectors.toList());
					userIds.addAll(carryOutIds);
				}

//				if (CollectionUtil.isNotEmpty(userIds)) {
//					List<EmployeeResp> chageeUserDetailList = personnelThirdService.getChageeUserDetailList(userIds);
//					Map<Long, EmployeeResp> employeeRespMap = chageeUserDetailList.stream().collect(Collectors.toMap(EmployeeResp::getId, Function.identity(), (s1, s2) -> s1));
//					storeTaskRelationDetailResponse.setManageName(builderUser(employeeRespMap, storeManageJsonBO.getManageId()));
//					storeTaskRelationDetailResponse.setCarryOutName(builderUser(employeeRespMap, storeCarryOutJsonBO.getCarryOutId()));
//				}
			}
//			if (Objects.isNull(storeTaskRelationDetailResponse.getSupplierEntryDate()) && Objects.isNull(storeTaskRelationDetailResponse.getBillingStartDate())) {
//				//供应商进场日期/计费开始日期：为门店工单信息中最早的那一条的创建时间
//				LambdaQueryWrapper<WorkOrderDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//				lambdaQueryWrapper.eq(WorkOrderDO::getStoreCode, storeDO.getStoreNo()).eq(WorkOrderDO::getDeleteFlag, NumberUtils.INTEGER_ZERO)
//					.orderByAsc(WorkOrderDO::getCreateTime).last("limit 1");
//				WorkOrderDO workOrderDO = workOrderBaseService.getOne(lambdaQueryWrapper);
//				if (Objects.nonNull(workOrderDO) && Objects.nonNull(workOrderDO.getCreateTime())) {
//					storeTaskRelationDetailResponse.setSupplierEntryDate(workOrderDO.getCreateTime());
//					storeTaskRelationDetailResponse.setBillingStartDate(workOrderDO.getCreateTime());
//				}
//			}
			// GMV（近3月/近1年）第三方提供接口，时间支持T-1的
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new Date());
			// 减去一天
			calendar.add(Calendar.DAY_OF_YEAR, -1);
			// 获取前一天的日期
			Date previousDate = calendar.getTime();
			String format = dateFormat2.format(previousDate);
			JSONObject gmv = getGMV(request.getStoreNo(), format);
			if (!gmv.isEmpty()) {
				String gmv_month3 = String.valueOf(gmv.get("gmv_month3"));
				if (StringUtils.isNotBlank(gmv_month3)) {
					storeTaskRelationDetailResponse.setThreeMonthsGmv(gmv_month3);
					/*if (gmv_month3.contains(".")) {
						storeTaskRelationDetailResponse.setThreeMonthsGmv(gmv_month3.substring(0, gmv_month3.indexOf('.') + 3));
					} else {
						storeTaskRelationDetailResponse.setThreeMonthsGmv(gmv_month3);
					}*/
				}
				String gmv_year = String.valueOf(gmv.get("gmv_year"));
				if (StringUtils.isNotBlank(gmv_year)) {
					storeTaskRelationDetailResponse.setOneYearGmv(gmv_year);
					/*if (gmv_year.contains(".")) {
						storeTaskRelationDetailResponse.setOneYearGmv(gmv_year.substring(0, gmv_year.indexOf('.') + 3));
					} else {
						storeTaskRelationDetailResponse.setOneYearGmv(gmv_year);
					}*/
				}
			}
			//任务配置信息
			LambdaQueryWrapper<StoreTaskRelationDO> wrapper = new LambdaQueryWrapper<>();
			wrapper.eq(StoreTaskRelationDO::getStoreNo, storeDO.getStoreNo());
			List<TaskRelationDetailResponse> storeTaskRelationResponseList = new ArrayList<>();
			List<StoreTaskRelationDO> storeTaskRelationDOList = storeTaskRelationMapper.selectList(wrapper);
			if (CollectionUtils.isNotEmpty(storeTaskRelationDOList)) {
				for (StoreTaskRelationDO storeTaskRelationDO : storeTaskRelationDOList) {
					TaskRelationDetailResponse storeTaskRelationResponse = new TaskRelationDetailResponse();
					BeanUtils.copyProperties(storeTaskRelationDO, storeTaskRelationResponse);
					storeTaskRelationResponse.setPicture(JSON.parseArray(storeTaskRelationDO.getPicture(), TaskRelationDetailResponse.FileVO.class));
					storeTaskRelationResponseList.add(storeTaskRelationResponse);
				}
				storeTaskRelationDetailResponse.setTaskRelationDetailResponseList(storeTaskRelationResponseList);
			}
		}
		return storeTaskRelationDetailResponse;
	}

	/**
	 * 获取门店的GMV数据信息
	 *
	 * @return jsonObject
	 */
	public JSONObject getGMV(String storeCodeParam, String ptParam) {
		// 创建HttpClient实例
		CloseableHttpClient httpClient = HttpClients.createDefault();
		JSONObject jsonObject = new JSONObject();
		if (StringUtils.isBlank(storeCodeParam) && StringUtils.isBlank(ptParam)) {
			throw new BizException(BizErrorCode.GMV_REQUEST_IS_NULL.getErrorMsg());
		}
		try {
			// 设置请求的URL+设置请求的参数（Query）
			HttpPost httpPost = new HttpPost(gmvUrl.concat(gmvStoreCode).concat(storeCodeParam).concat(gmvPt).concat(ptParam));
			log.info("请求的URL+请求的参数（Query）为: {}", httpPost);
			// 设置请求的Header
			httpPost.setHeader("Authorization", gmvAuthorization);
			httpPost.setHeader("Content-Type", "application/json");
			log.info("请求的Authorization: {}", gmvAuthorization);
			// 发送请求并获取响应
			HttpResponse response = httpClient.execute(httpPost);
			log.info("获取门店{}时间为{}的GMV值返回对象: {}", storeCodeParam, ptParam, response);
			// 从响应中获取内容
			String responseContent = EntityUtils.toString(response.getEntity());
			log.info("获取门店{}时间为{}的GMV值返回对象获取entity: {}", storeCodeParam, ptParam, responseContent);
			JSONObject jsonObject1 = JSONObject.parseObject(responseContent);
			log.info("entity转换程json对象: {}", jsonObject1);
			if (Objects.nonNull(jsonObject1) && "success".equals(jsonObject1.get("errMsg"))) {
				JSONArray data = (JSONArray) jsonObject1.get("data");
				log.info("获取json对象的data信息: {}", data);
				if (CollectionUtils.isNotEmpty(data)) {
					jsonObject = (JSONObject) data.get(0);
					log.info("获取data信息的值: {}", jsonObject);
					//处理科学计数
					Double gmv_month3 = jsonObject.getDoubleValue("gmv_month3");
					Double gmv_year = jsonObject.getDoubleValue("gmv_year");
					jsonObject = new JSONObject();
					jsonObject.put("gmv_month3",gmv_month3);
					jsonObject.put("gmv_year",gmv_year);
				}
			} else {
//				throw new BizException("获取门店{}的GMV信息失败！", storeCodeParam);
				log.info("获取门店{}的GMV信息失败！", storeCodeParam);
			}
		} catch (Exception e) {
//			throw new BizException("获取门店{}的GMV信息失败！", storeCodeParam);
			log.info("调用数仓接口出现异常");
		}
		return jsonObject;
	}

	//删除门店任务
	public Boolean deleteStoreTaskRelation(List<Long> ids) {
		if (CollectionUtils.isNotEmpty(ids)) {
			for (Long id : ids) {
				LambdaQueryWrapper<StoreTaskRelationDO> wrapper = new LambdaQueryWrapper();
				wrapper.eq(StoreTaskRelationDO::getId,id);
				storeTaskRelationMapper.delete(wrapper);
			}
		}
		return true;
	}

	// 门店添加任务 查询可配置的基础任务  done 双set改造
	public StoreTaskRelation2SetVO addStoreTaskQueryBasicTask(String storeNo) {
		StoreTaskRelation2SetVO storeTaskRelation2SetVO = new StoreTaskRelation2SetVO();
		//List<TaskInfo> multiple = storeTaskConfig.getMultiple();
		Map<String,String> taskMap = JSONObject.parseObject(multiple, Map.class);

		//B set 已配置任务
		LambdaQueryWrapper<StoreTaskRelationDO> wrapper2 = new LambdaQueryWrapper<>();
		wrapper2.eq(StoreTaskRelationDO::getStoreNo, storeNo);
		wrapper2.eq(StoreTaskRelationDO::getDeleteFlag,CommonConstant.NOT_DELETE_FLAG);
		List<StoreTaskRelationDO> storeTaskRelationDOList = storeTaskRelationMapper.selectList(wrapper2);
		List<StoreTaskRelationExistResponse> bSet = new ArrayList<>();
		for (StoreTaskRelationDO storeTaskRelationDO : storeTaskRelationDOList) {
			StoreTaskRelationExistResponse storeTaskRelationResponse = new StoreTaskRelationExistResponse();
			if (taskMap.containsKey(storeTaskRelationDO.getTaskId())){
				String taskCount = taskMap.get(storeTaskRelationDO.getTaskId());
				storeTaskRelationResponse.setTotalCount(taskCount);
			}else {
				storeTaskRelationResponse.setTotalCount(CommonConstant.TASK_COUNT); // 未配置默认配置为1
			}
			BeanUtils.copyProperties(storeTaskRelationDO, storeTaskRelationResponse);
			List<StoreTaskRelationExistResponse.FileVO> pictureList = JSON.parseArray(storeTaskRelationDO.getPicture(), StoreTaskRelationExistResponse.FileVO.class);
			storeTaskRelationResponse.setPicture(pictureList);
			storeTaskRelationResponse.setTaskIdAndTaskName(storeTaskRelationDO.getTaskId().concat(storeTaskRelationDO.getTaskName()));
			bSet.add(storeTaskRelationResponse);
		}
		Map<String, List<StoreTaskRelationDO>> map = storeTaskRelationDOList.stream().collect(Collectors.groupingBy(StoreTaskRelationDO::getTaskId));

		//A set 可配置任务
		LambdaQueryWrapper<BasicTaskDO> wrapper = new LambdaQueryWrapper();
		wrapper.eq(BasicTaskDO::getTaskStatus, NumberUtils.INTEGER_ZERO);
		wrapper.eq(BasicTaskDO::getDeleteFlag, CommonConstant.NOT_DELETE_FLAG);
		List<BasicTaskDO> basicTaskDOS = basicTaskConfigurationMapper.selectList(wrapper);
		log.info("查询库里数据:{}",JSON.toJSONString(basicTaskDOS));
		Set<StoreTaskRelationResponse> aSet = new HashSet<>();
		for (BasicTaskDO basicTaskDO : basicTaskDOS) {
			StoreTaskRelationResponse storeTaskRelationResponse = new StoreTaskRelationResponse();
			if (taskMap.containsKey(basicTaskDO.getTaskId())){//todo 待优化动态配置
				String taskCount = taskMap.get(basicTaskDO.getTaskId());
				storeTaskRelationResponse.setTotalCount(taskCount);
			}else {
				storeTaskRelationResponse.setTotalCount(CommonConstant.TASK_COUNT);
			}
			int count=Integer.parseInt(storeTaskRelationResponse.getTotalCount());
			if (MapUtil.isNotEmpty(map)){
				List<StoreTaskRelationDO> taskRelationDOS = map.get(basicTaskDO.getTaskId());
				if (CollectionUtils.isNotEmpty(taskRelationDOS)){
					//可配置数量
					count = Integer.parseInt(storeTaskRelationResponse.getTotalCount()) - taskRelationDOS.size();
				}
				if (map.keySet().contains(basicTaskDO.getTaskId()) && Integer.parseInt(storeTaskRelationResponse.getTotalCount()) == taskRelationDOS.size()){
					continue;
				}
			}
			storeTaskRelationResponse.setCount(String.valueOf(count));
			BeanUtils.copyProperties(basicTaskDO, storeTaskRelationResponse);
			storeTaskRelationResponse.setId(null);
			List<StoreTaskRelationResponse.FileVO> pictureList = JSON.parseArray(basicTaskDO.getPicture(), StoreTaskRelationResponse.FileVO.class);
			storeTaskRelationResponse.setPicture(pictureList);
			aSet.add(storeTaskRelationResponse);
		}
		//A-B差集
		//aSet.removeAll(bSet);
		//可选任务 A-B差集
		storeTaskRelation2SetVO.setSelectable(aSet);
		// 已选 B
		storeTaskRelation2SetVO.setSelected(bSet);
		return storeTaskRelation2SetVO;
	}


	public Boolean addStoreTaskSave(StoreTaskRelationDetailParam request) {
		// 锁的名称:阻止重复数据锁（可以根据实际情况设置）
		PreventRepeatLock lock = null;
		if (Objects.nonNull(request.getStoreNo())) {
			lock = new PreventRepeatLock(request.getStoreNo());
		}
		try {
			redisLockService.lockElseThrowError(lock, BizErrorCode.LOCK_EXCEPTION.getErrorMsg());
			StoreDO storeDO = storeBaseService.queryStoreByStoreNo(request.getStoreNo());
			if (!NumberUtils.INTEGER_ONE.equals(storeDO.getClosingTaskStatus())) {
				throw new BizException(BizErrorCode.CLOSE_CLEAN_DISABLE);
			}
			// 执行插入操作
			if (CollectionUtils.isNotEmpty(request.getAddList())) {
				Set<String> addlist = request.getAddList().stream().map(StoreTaskRelationInfo::getTaskId).collect(Collectors.toSet());
				LambdaQueryWrapper<BasicTaskDO> basicTaskWrapper = new LambdaQueryWrapper<>();
				List<BasicTaskDO> basicTasks = basicTaskConfigurationService.list(basicTaskWrapper.in(BasicTaskDO::getTaskId,addlist));
				Map<String, BasicTaskDO> basicTaskMap = basicTasks.stream().collect(Collectors.toMap(BasicTaskDO::getTaskId, Function.identity(), (a, b) -> b));

				//无id则添加
				List<StoreTaskRelationInfo> relationInfo = request.getAddList().stream().filter(s -> ObjectUtils.isEmpty(s.getId())).collect(Collectors.toList());

				List<StoreTaskRelationDO> insertDO = Lists.newArrayListWithExpectedSize(relationInfo.size());
				for (StoreTaskRelationInfo insertData : relationInfo) {
					StoreTaskRelationDO insertValue = new StoreTaskRelationDO();
					BeanUtils.copyProperties(insertData, insertValue);
					BasicTaskDO basicTask = basicTaskMap.get(insertData.getTaskId());
					insertValue.setPicture(basicTask.getPicture());
					insertValue.setWordDescribe(basicTask.getWordDescribe());
					insertValue.setModify(NumberUtils.INTEGER_ZERO);
					insertDO.add(insertValue);
				}
				storeTaskRelationBaseService.saveBatch(insertDO);
			}
			if (CollectionUtils.isNotEmpty(request.getDeleteList())){
				storeTaskRelationMapper.deleteBatchIds(request.getDeleteList().stream().map(StoreTaskRelationInfo::getId).collect(Collectors.toList()));
			}
		} finally {
			// 释放锁
			redisLockService.unLock(lock);
		}
		return true;
	}


	@Transactional(rollbackFor = Exception.class)
	public Boolean updateStoreDetailData(UpdateDateRequest request) {
		//获取门店基础信息
		List<StoreConfigurationDO> storeConfigurationDOList = storeConfigurationBaseService.getByStoreCode(request.getStoreNo());
		StoreConfigurationDO storeConfigurationDO;
		if (CollectionUtils.isNotEmpty(storeConfigurationDOList)) {
			storeConfigurationDO = storeConfigurationDOList.get(0);
			storeConfigurationDO.setUpdateTime(new Date());
		} else {
			storeConfigurationDO = new StoreConfigurationDO();
		}
		try {
			//处理 供应商进场日期/计费开始日期 转换
			if (StringUtils.isNotBlank(request.getSupplierEntryDate())) {
				Date supplierEntryDate = dateFormat.parse(request.getSupplierEntryDate());
				storeConfigurationDO.setSupplierEntryDate(supplierEntryDate);
			}
			if (StringUtils.isNotBlank(request.getBillingStartDate())) {
				Date billingStartDate = dateFormat.parse(request.getBillingStartDate());
				storeConfigurationDO.setBillingStartDate(billingStartDate);
			}
		} catch (ParseException e) {
			throw new BizException(BizErrorCode.SUPPLIER_ENTRY_BILLING_START_DATA);
		}
		storeConfigurationDO.setStoreCode(request.getStoreNo());
		storeConfigurationDO.setClosingWorkOrderCreateTime(request.getClosingWorkOrderCreateTime());
		storeConfigurationDO.setClosingWorkOrderAcceptanceTime(request.getClosingWorkOrderAcceptanceTime());
		storeConfigurationDO.setSupplierNo(request.getSupplierNo());
		storeConfigurationDO.setSupplierName(request.getSupplierName());
		BigDecimal floorPrice = new BigDecimal(request.getFloorPrice());
		storeConfigurationDO.setFloorPrice(floorPrice);
		storeConfigurationDO.setManage(request.getManageList());
		storeConfigurationDO.setCarryOut(request.getCarryOutList());
		if (StringUtils.isNotBlank(request.getNightFloorPrice())) {
			BigDecimal nightFloorPrice = new BigDecimal(request.getNightFloorPrice());
			storeConfigurationDO.setNightFloorPrice(nightFloorPrice);
		}
		if (ObjectUtils.isNotEmpty(storeConfigurationDO.getId())){
			StoreConfigLock lock = null;
			if (Objects.nonNull(request.getStoreNo())) {
				lock = new StoreConfigLock(request.getStoreNo());
			}
			try {
				redisLockService.lockElseThrowError(lock, BizErrorCode.LOCK_EXCEPTION.getErrorMsg());
				storeConfigurationMapper.update(storeConfigurationDO, Wrappers.<StoreConfigurationDO>lambdaUpdate()
					.set(StoreConfigurationDO::getBillingStartDate, StringUtils.isBlank(request.getBillingStartDate())? null : request.getBillingStartDate())
					.set(StoreConfigurationDO::getNightFloorPrice, StringUtils.isBlank(request.getNightFloorPrice()) ? null : new BigDecimal(request.getNightFloorPrice()))
					.eq(StoreConfigurationDO::getId, storeConfigurationDO.getId()));

				List<ManageInfo> manageInfos = JSON.parseObject(request.getManageList(), new TypeReference<List<ManageInfo>>() {
				});
				List<String> manageUserIds = manageInfos.stream().map(ManageInfo::getManagerUserId).filter(StringUtils::isNotBlank).collect(Collectors.toList());
				storePersonnelBizService.addUserRole(manageUserIds, managerRoleId);

				List<CarryOutInfo> carryOutInfos = JSON.parseObject(request.getCarryOutList(), new TypeReference<List<CarryOutInfo>>() {
				});
				List<String> carryOutUserIds = carryOutInfos.stream().map(CarryOutInfo::getCarryOutUserId).filter(StringUtils::isNotBlank).collect(Collectors.toList());
				storePersonnelBizService.addUserRole(carryOutUserIds, carryOutRoleId);

			} finally {
				redisLockService.unLock(lock);
			}
		}else {
			return storeConfigurationBaseService.saveOrUpdate(storeConfigurationDO);
		}
		return true;
	}

	public PaginationData<SearchSupplierResponse> searchSupplier(PaginationRequest<SearchSupplierRequest> request) {
		SearchSupplierRequest queryParameter = request.getQueryParameter();

		PaginationRequest<SearchSupplierBaseBO> paginationRequest = new PaginationRequest<>();
		paginationRequest.setPageNum(request.getPageNum());
		paginationRequest.setPageSize(request.getPageSize());
		SearchSupplierBaseBO baseBO = new SearchSupplierBaseBO();
		baseBO.setName(queryParameter.getName());
		baseBO.setCode(queryParameter.getCode());
		baseBO.setChannelType(CommonConstant.INTEGER_THREE);
		baseBO.setSupplierCategoryId(Long.parseLong(supplierCategoryId));
		paginationRequest.setQueryParameter(baseBO);
		PaginationData<SupplierBaseBO> supplierPageData = scmThirdService.searchSupplier(paginationRequest);

		if (Objects.isNull(supplierPageData) || CollectionUtils.isEmpty(supplierPageData.getPageList())) {
			return ResponseUtil.emptyResponse(request, SearchSupplierResponse.class, NumberUtils.LONG_ZERO);
		}
		List<SupplierBaseBO> pageList = supplierPageData.getPageList();

		List<SearchSupplierResponse> responseList = pageList.stream().map(s -> {
			SearchSupplierResponse supplierResponse = new SearchSupplierResponse();
			BeanUtil.copyProperties(s, supplierResponse);
			return supplierResponse;
		}).collect(Collectors.toList());
		return ResponseUtil.commonResponse(request, responseList, supplierPageData.getTotal());
	}

	private String builderUser(Map<Long, EmployeeResp> employeeRespMap, String userIdList) {
		List<String> userIds = StrUtil.split(userIdList, CommonConstant.OR_STRING);
		if (CollectionUtil.isEmpty(userIds)) {
			return StringUtils.EMPTY;
		}
		List<EmployeeResp> resps = new ArrayList<>();
		for (String userId : userIds) {
			EmployeeResp employeeResp = employeeRespMap.get(Long.parseLong(userId));
			resps.add(employeeResp);
		}
		return resps.stream().map(EmployeeResp::getRealName).filter(StringUtils::isNotBlank).collect(Collectors.joining(CommonConstant.OR_STRING));

	}

}
